/*
 * @Author: dazy916 dazy916@126.com
 * @Date: 2025-07-29 16:53:40
 * @LastEditors: dazy dazy916@126.com
 * @LastEditTime: 2025-09-19 17:03:08
 * @FilePath: \digitalhuman\src\store\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useChatStore = defineStore('chat', () => {
    const messages = ref([])
    const isLoading = ref(false)
    const isStreaming = ref(false)
    const abortController = ref(null)
    const history=ref(null)
    const loginType=ref(null)
    const platform=ref(null)

    // Initialize token from localStorage
    const token = ref(localStorage.getItem('chat_token') || null)

    // Initialize userInfo from localStorage
    const userInfo = ref(
        localStorage.getItem('chat_userInfo')
            ? JSON.parse(localStorage.getItem('chat_userInfo'))
            : null
    )

    const addMessage = (message) => {
        messages.value.push(message)
    }

    const updateLastMessage = (content) => {
        if (messages.value.length > 0) {
            const lastMessage = messages.value[messages.value.length - 1]
            if (lastMessage.role === 'assistant') {
                lastMessage.content += content
            }
        }
    }
    const setLoginType=(type)=>{
        loginType.value=type
    }
    // Set token and cache it
    const setToken = (newToken) => {
        token.value = newToken
        if (newToken) {
            localStorage.setItem('chat_token', newToken)
        } else {
            localStorage.removeItem('chat_token')
        }
    }

    // Set userInfo and cache it
    const setUserInfo = (info) => {
        userInfo.value = info
        if (info) {
            localStorage.setItem('chat_userInfo', JSON.stringify(info))
        } else {
            localStorage.removeItem('chat_userInfo')
        }
    }

    // Clear all user data (for logout)
    const clearUserData = () => {
        token.value = null
        userInfo.value = null
        localStorage.removeItem('chat_token')
        localStorage.removeItem('chat_userInfo')
    }

    return {
        messages,
        isLoading,
        isStreaming,
        abortController,
        token,
        userInfo,
        history,
        loginType,
        platform,
        addMessage,
        updateLastMessage,
        setToken,
        setUserInfo,
        clearUserData,
        setLoginType
    }
})